package com.project.fortuneteller.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smartjavaai.common.entity.face.FaceSearchResult;
import cn.smartjavaai.face.config.FaceRecConfig;
import cn.smartjavaai.face.entity.FaceRegisterInfo;
import cn.smartjavaai.face.enums.FaceRecModelEnum;
import cn.smartjavaai.face.factory.FaceRecModelFactory;
import cn.smartjavaai.face.model.facerec.FaceRecModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.project.fortuneteller.common.Constants;
import com.project.fortuneteller.pojo.dto.RegisterFaceDTO;
import com.project.fortuneteller.pojo.vo.LoginFaceVO;
import com.project.fortuneteller.pojo.vo.RegisterFaceVO;
import com.project.fortuneteller.service.FaceCheckService;
import com.project.fortuneteller.utils.FaceRecUtils;
import com.project.fortuneteller.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
 * 人脸识别服务实现类
 * @author 16905
 */
@Slf4j
@Service
public class FaceCheckServiceImpl implements FaceCheckService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 人脸识别模型配置
    private final FaceRecConfig config = new FaceRecConfig();

    public FaceCheckServiceImpl() {
        // 初始化人脸识别模型配置
        initFaceRecConfig();
    }

    /**
     * 初始化人脸识别模型配置
     */
    private void initFaceRecConfig() {
        try {
            config.setModelEnum(FaceRecModelEnum.ELASTIC_FACE_MODEL);
            log.info("人脸识别模型配置初始化完成");
        } catch (Exception e) {
            log.error("人脸识别模型配置初始化失败: {}", e.getMessage(), e);
        }
    }

    @Override
    public Result registerFace(RegisterFaceVO registerFaceVO) {
        // 参数非空校验
        if (registerFaceVO == null) {
            return Result.error("注册信息不能为空");
        }
        if (registerFaceVO.getUserId() == null || registerFaceVO.getUserId().trim().isEmpty()) {
            return Result.error("用户ID不能为空");
        }

        if (registerFaceVO.getBase64String() == null || registerFaceVO.getBase64String().trim().isEmpty()) {
            return Result.error("图片数据不能为空");
        }

        try {
            String base64String = registerFaceVO.getBase64String();
            String base64Data = base64String;

            // 处理Base64字符串前缀
            if (base64String.contains(",")) {
                base64Data = base64String.substring(base64String.indexOf(",") + 1);
            }

            // 解码Base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 将字节数组转换为BufferedImage
            try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
                BufferedImage image = ImageIO.read(bis);
                if (image == null) {
                    return Result.error("图片格式不正确");
                }

                String result = FaceRecUtils.registerFace(image, registerFaceVO.getUserId(), registerFaceVO.getRoleId());
                if (result == null) {
                    return Result.error("人脸注册失败");
                }

                log.info("人脸注册成功，用户ID: {}, 角色ID: {}", registerFaceVO.getUserId(), registerFaceVO.getRoleId());
                return Result.success(result);
            }
        } catch (IllegalArgumentException e) {
            log.error("Base64解码失败: {}", e.getMessage(), e);
            return Result.error("图片数据格式错误");
        } catch (IOException e) {
            log.error("图片处理异常: {}", e.getMessage(), e);
            return Result.error("图片处理失败");
        } catch (Exception e) {
            log.error("人脸注册异常: {}", e.getMessage(), e);
            return Result.error("人脸注册失败，系统异常");
        }
    }

    @Override
    public String loginFace(LoginFaceVO loginFaceVO) {
        // 参数非空校验
        try {
            String base64String = loginFaceVO.getBase64String();
            String base64Data = base64String;

            // 处理Base64字符串前缀
            if (base64String.contains(",")) {
                base64Data = base64String.substring(base64String.indexOf(",") + 1);
            }

            // 解码Base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 将字节数组转换为BufferedImage
            try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
                BufferedImage image = ImageIO.read(bis);
                if (image == null) {
                    return null;
                }
                FaceSearchResult faceSearchResult = FaceRecUtils.queryFace(image);
                if (faceSearchResult == null) {
                    return null;
                }

                // 相似度阈值检查
                if (faceSearchResult.getSimilarity() > Constants.FACE_SIMILARITY_THRESHOLD) {
                    log.info("人脸登录成功，用户ID: {}, 相似度: {}", loginFaceVO.getUserId(), faceSearchResult.getSimilarity());
                    return faceSearchResult.getMetadata();
                }
                return null;
            }
        } catch (IllegalArgumentException e) {
            log.error("Base64解码失败: {}", e.getMessage(), e);
            return null;
        } catch (IOException e) {
            log.error("图片处理异常: {}", e.getMessage(), e);
            return null;
        } catch (Exception e) {
            log.error("人脸登录异常: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Result updateFace(RegisterFaceDTO registerFaceDTO) {
        // 参数非空校验
        if (registerFaceDTO == null) {
            return Result.error("更新信息不能为空");
        }
        if (registerFaceDTO.getName() == null || registerFaceDTO.getName().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (registerFaceDTO.getBase64String() == null || registerFaceDTO.getBase64String().trim().isEmpty()) {
            return Result.error("图片数据不能为空");
        }

        try {
            String base64String = registerFaceDTO.getBase64String();
            String base64Data = base64String;

            // 处理Base64字符串前缀
            if (base64String.contains(",")) {
                base64Data = base64String.substring(base64String.indexOf(",") + 1);
            }

            // 解码Base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);

            // 将字节数组转换为BufferedImage
            try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
                BufferedImage image = ImageIO.read(bis);
                if (image == null) {
                    return Result.error("图片格式不正确");
                }

                // 这里需要传入faceId，但DTO中没有，需要根据实际情况调整
                // FaceRecUtils.updateFace(image, registerFaceDTO.getName(), "role", "faceId");

                log.info("人脸更新成功，用户名: {}", registerFaceDTO.getName());
                return Result.success("人脸更新成功");
            }
        } catch (IllegalArgumentException e) {
            log.error("Base64解码失败: {}", e.getMessage(), e);
            return Result.error("图片数据格式错误");
        } catch (IOException e) {
            log.error("图片处理异常: {}", e.getMessage(), e);
            return Result.error("图片处理失败");
        } catch (Exception e) {
            log.error("人脸更新异常: {}", e.getMessage(), e);
            return Result.error("人脸更新失败，系统异常");
        }
    }

    @Override
    public Result deleteFace(String faceId) {
        // 参数非空校验
        if (faceId == null || faceId.trim().isEmpty()) {
            return Result.error("人脸ID不能为空");
        }

        try {
            FaceRecUtils.deleteFace(faceId);
            log.info("人脸删除成功，人脸ID: {}", faceId);
            return Result.success("人脸删除成功");
        } catch (Exception e) {
            log.error("人脸删除异常: {}", e.getMessage(), e);
            return Result.error("人脸删除失败，系统异常");
        }
    }
}
